package main

import (
	//"bytes"
	//"fmt"
	"io/ioutil"
	"log"
	//"os"
	"os/exec"
	"time"
)

var (
	cmd     *exec.Cmd
	started chan bool
	//out     bytes.Buffer
	//stdout
)

func Kill() {
	defer func() {
		if e := recover(); e != nil {
			log.Println("Kill.recover -> ", e)
		}
	}()
	if cmd != nil && cmd.Process != nil {
		err := cmd.Process.Kill()
		if err != nil {
			log.Println("Kill -> ", err)
		}
	}
}

func Restart() {
	log.Println("kill running process1")
	Kill()
	go Start()
}

func Start() {

	appname := "tk.exe"
	//appname := "sh -c 'echo \"START\" && sleep 5 && echo \"END\"'"

	cmd = exec.Command(appname)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Println("StdoutPipe: " + err.Error())
		return
	}
	//cmd.Stdout = os.Stdout
	//cmd.Stdout = &out
	//cmd.Stderr = os.Stderr

	cmd.Start()

	//started <- true

	bytes, err := ioutil.ReadAll(stdout)
	if err != nil {
		log.Println("ReadAll stdout: ", err.Error())
		return
	}

	if err := cmd.Wait(); err != nil {
		log.Println("Wait: ", err.Error())
		return
	}

	log.Printf("stdout: %s", bytes)
}

func main() {
	Restart()

	<-time.After(time.Second * 1)
	log.Println("kill running process2")
	Kill()
	log.Println("kill running process3")
	//log.Println("out:",out.String())
}
